part of 'kit.dart';

class Sms implements Jsonable {
  /// 通常为4位数的纯数字
  final String code;
  final DateTime createAt;
  final DateTime expireAt;

  Sms({
    required this.code,
    required this.createAt,
    required this.expireAt,
  });

  /// 新建一个4位数验证码，只要指定过期时间和手机号
  factory Sms.create({required Duration expireTime}) => Sms(
        code: Generate.number(4),
        createAt: DateTime.now(),
        expireAt: DateTime.now() + (expireTime),
      );

  factory Sms.fromRaw(Json raw) => Sms(
        code: raw["code"],
        createAt: DateTime.parse(raw["createAt"]),
        expireAt: DateTime.parse(raw["expireAt"]),
      );

  /// 当现在已经超过了"过期时间"时，就判定验证码已过期
  bool get hasExpired => DateTime.now() >= expireAt;

  /// 当发送还没有超过30秒时，不可以再发送第二条
  bool get isCooldown =>
      DateTime.now().difference(createAt) < Duration(seconds: 30);

  @override
  Json toJson() => {
        "code": code,
        "createAt": createAt.toString(),
        "expireAt": expireAt.toString(),
      };
}
